package upload

import (
	"github.com/gogf/gf/v2/net/ghttp"
	"github.com/gogf/gf/v2/os/gctx"
	"uni-crawl-frame/db/mysql/dao"
	"uni-crawl-frame/db/mysql/model/entity"
	"uni-crawl-frame/entity/crawldto"
	"uni-crawl-frame/service/crawl/uploadservice"
	"uni-crawl-frame/utils/httputil"
)

var (
	CmdExe  = new(cmdExe)
	columns = dao.CmsUploadQueue.Columns()
)

type cmdExe struct{}

// 创建上传任务
func (c *cmdExe) CreateTask(r *ghttp.Request) {

	create := new(crawldto.CmsUploadQueueCreate)
	httputil.ParseParam(r, create)

	// 校验文件
	upFile := r.GetUploadFile("file")
	if upFile == nil {
		httputil.Error(r, "上传文件不能为空")
	}

	dbQueue := uploadservice.GetByVideoItemId(create.VideoItemId, uploadservice.Uploading)
	if dbQueue != nil {
		httputil.Error(r, "已经在上传中,不能重复上传："+upFile.Filename)
	}

	uploadQueue := entity.CmsUploadQueue{
		HostIp:       create.HostIp,
		FileSize:     upFile.Size,
		CountryCode:  create.CountryCode,
		VideoCollId:  create.VideoCollId,
		VideoItemId:  create.VideoItemId,
		UploadStatus: uploadservice.Uploading,
		FileType:     uploadservice.FileTypeVideo,
		//CreateUser:   create.CreateUser,
	}

	_, err := dao.CmsUploadQueue.Ctx(gctx.GetInitCtx()).Insert(uploadQueue)
	if err != nil {
		httputil.Error(r, "创建任务失败")
	}
	httputil.Success(r)
}

// 改变任务状态
func (c *cmdExe) UpdateTaskStatus(r *ghttp.Request) {
	cmd := new(crawldto.CmsUploadQueueCmd)
	httputil.ParseParam(r, cmd)

	do := uploadservice.GetById(cmd.Id)
	if do == nil {
		httputil.Error(r, "不存在该任务")
	}

	uploadservice.UpdateById(do, cmd.UploadStatus)
	httputil.Success(r)

}
